package com.ssyc.gsk_teacher.activity;

import android.content.Intent;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.base.Constants;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.BqaManager;
import com.ssyc.common.manager.PopUpManager;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.SnackbarUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.MyGridView;
import com.ssyc.gsk_teacher.R;
import com.ssyc.gsk_teacher.adapter.ClassGvAdapter;
import com.ssyc.gsk_teacher.adapter.TeamRvAdapter;
import com.ssyc.gsk_teacher.bean.ClassInfo;
import com.ssyc.gsk_teacher.bean.TeamInfo;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 学生档案
 * Created by Administrator on 2018/6/25 0025.
 */

public class TeacherStudentFileActivity extends BaseActivity implements View.OnClickListener {

    //返回键
    private ImageView ivBack;
    //选择班级
    private ImageView ivChooseClass;
    //展示小组的列表
    private RecyclerView rv;

    //班级名称
    private TextView tvClassName;

    //标题栏的布局
    private LinearLayout llTitle;

    //内容布局
    private RelativeLayout rlContent;

    //加载框布局
    private RelativeLayout rlLoading;

    //所有班级的列表
    private List<ClassInfo.ListBean> classInfos;

    //是否获取班级列表数据完成的标识,没完成之前点击选择班级的弹框提示正在加载,不允许点击
    private boolean isLoadClassCompleted;

    //记录弹出展示班级列表PopUpWindow的选中位置的值,默认第一个被选中
    private int popSelectedPos = 0;

    //展示班级列表的适配器
    private ClassGvAdapter classGvAdapter;

    //班级对应的小组数据集合
    private List<TeamInfo.TeamsinfoBean> teamsinfos;

    //展示小组列表的适配器
    private TeamRvAdapter teamAdapter;


    //Handler对象,用于延迟关闭Pop
    private Handler handler = new Handler();

    //班级组的数据对象
    private TeamInfo info;


    //请求码
    private static int REQUEST_CODE = 0x230;
    private ImageView iv_add_student;

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.teacher_activity_student_file;
    }

    @Override
    protected void init() {

        showContent();

        //初始化视图
        initView();

        //请求服务器数据获取班级列表
        httpClass();

    }

    /**
     * 初始化视图
     */
    public void initView() {

        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        ivChooseClass = findViewById(R.id.iv_choose_class);
        ivChooseClass.setOnClickListener(this);
        rv = findViewById(R.id.rv);
        rlContent = findViewById(R.id.rl_content);
        rlLoading = findViewById(R.id.rl_loading);
        rlContent.setVisibility(View.GONE);
        rlLoading.setVisibility(View.VISIBLE);
        //标题栏
        llTitle = findViewById(R.id.ll_title);

        //班级名称
        tvClassName = findViewById(R.id.tv_class_name);
        tvClassName.setOnClickListener(this);

        //添加学生
        iv_add_student = findViewById(R.id.iv_add_student);
        iv_add_student.setOnClickListener(this);

    }


    /**
     * 获取班级列表的数据
     */
    private void httpClass() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "5");
        map.put("c", AccountUtils.getAccount(this));
        map.put("user_type", AccountUtils.getUserType(this));
        map.put("platform", "8");
        HttpUtils.post(HttpAdress.GETCLASS, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (null != rlLoading && rlLoading.getVisibility() != View.GONE) {
                    rlLoading.setVisibility(View.GONE);
                }
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {
                ClassInfo info = null;
                try {
                    info = GsonUtil.jsonToBean(response, ClassInfo.class);
                } catch (Exception e) {
                    Log.i("test", "数据解析异常");
                }

                if (null != info) {
                    if ("1".equals(info.getStatus())) {
                        //返回成功
                        classInfos = info.getList();
                        if (null != classInfos && classInfos.size() != 0) {
                            //加载完班级列表数据后并且设置好列表展示数据后标题栏选择班级弹框可以进行点击了
                            isLoadClassCompleted = true;
                            //默认加载第一个班级的数据
                            httpTeam(popSelectedPos);
                        } else {
                            if (null != rlLoading && rlLoading.getVisibility() != View.GONE) {
                                rlLoading.setVisibility(View.GONE);
                            }
                            UiUtils.Toast("没有班级数据", false);

                            ivChooseClass.setVisibility(View.INVISIBLE);
                            iv_add_student.setVisibility(View.INVISIBLE);
                        }

                    } else {
                        //返回错误
                        UiUtils.Toast("服务器返回异常,状态码是:" + info.getStatus(), false);
                        Log.i("test", "服务器返回异常,状态码是:" + info.getStatus());
                    }

                } else {
                    Log.i("test", "服务器返回数据为空");
                }

            }
        });
    }

    /**
     * 根据当前记录的班级请求服务器获取班级小组的数据数据
     */
    private void httpTeam(int pos) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "7");
        map.put("c", AccountUtils.getAccount(this));
        map.put("user_type", AccountUtils.getUserType(this));
        map.put("platform", "8");
        map.put("classnum", classInfos.get(pos).getClassnum());

        HttpUtils.post(HttpAdress.GETEAM, map, this, new HttpUtils.CallBack() {

            @Override
            public void onError(Call call, Exception e, int id) {
                if (null != rlLoading && rlLoading.getVisibility() != View.GONE) {
                    rlLoading.setVisibility(View.GONE);
                }
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {

                if (null != rlLoading && rlLoading.getVisibility() != View.GONE) {
                    rlLoading.setVisibility(View.GONE);
                }
                //显示内容布局
                rlContent.setVisibility(View.VISIBLE);

                try {
                    info = GsonUtil.jsonToBean(response, TeamInfo.class);
                } catch (Exception e) {
                    Log.i("test", Constants.PARSEDATAERROR);
                }

                if (null != info) {
                    if ("1".equals(info.getStatus())) {

                        //设置班级名称
                        setClassName(info.getClassinfo().getName());

                        //返回成功
                        teamsinfos = info.getTeamsinfo();
                        if (null != teamsinfos && teamsinfos.size() != 0) {
                            //证明班级有小组
                            initTeamRv(teamsinfos);
                        } else {
                            //证明班级没有小组,这种情况不可能出现,服务器默认返回10个小组
                        }
                    } else {
                        //返回错误
                        UiUtils.Toast(Constants.ERRORSTATE + info.getStatus(), false);
                        Log.i("test", Constants.ERRORSTATE + info.getStatus());
                    }
                } else {
                    Log.i("test", Constants.EMPTY);
                }
            }
        });
    }


    /**
     * 设置班级名称
     *
     * @param name
     */
    private void setClassName(String name) {
        if (TextUtils.isEmpty(name)) {
            tvClassName.setText("暂无名称");
        } else {
            tvClassName.setText(name);
        }

    }

    /**
     * 设置班级小组的数据
     *
     * @param teamsinfos
     */
    private void initTeamRv(List<TeamInfo.TeamsinfoBean> teamsinfos) {
        teamAdapter = new TeamRvAdapter(this, this, R.layout.teacher_rv_team, teamsinfos);
        BqaManager.setRv(null, this, teamAdapter, rv);
    }


    /**
     * 点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            //返回
            finish();
        } else if (id == R.id.iv_choose_class) {
            //选择班级
            if (isLoadClassCompleted) {
                //弹出选择班级的PopUpWindow
                showClassPop();
            } else {
                //没加载完成
                SnackbarUtil.ShortSnackbar(llBaseMain, Constants.LOADING, 0).show();
            }
        } else if (id == R.id.tv_class_name) {
            //修改班级名称
            Intent intent = new Intent(this, TeacherUpdateClassNameActivity.class);
            intent.putExtra("classinfo", info);
            startActivityForResult(intent, REQUEST_CODE);
        } else if (id == R.id.iv_add_student) {
            //跳转到添加学生的界面
            UiUtils.startActivity(this, TeacherAddStudentActivity.class);
        }

    }

    /**
     * 回调结果
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            String className = data.getStringExtra("className");
            if (!TextUtils.isEmpty(className)) {
                tvClassName.setText(className);
                //同时更新展示班级列表的对应位置的班级名称
                if (classInfos != null && classInfos.size() != 0) {
                    classInfos.get(popSelectedPos).setName(className);
                    classGvAdapter.notifyDataSetChanged();
                }
            }
        }
    }

    /**
     * 弹出展示班级列表的PopUpWindow
     */
    private void showClassPop() {
        if (null == classInfos || classInfos.size() == 0) {
            //证明没有班级列表数据,不做任何操作
            return;
        } else {
            PopUpManager.showPop(this, R.layout.teacher_pop_class, 0.3f, llTitle, new PopUpManager.onGetViewListener() {
                @Override
                public void getChildView(View view, int layoutResId) {
                    //展示班级列表的GridView
                    MyGridView gv = view.findViewById(R.id.gv);

                    //第一步:设置默认的选中状态的班级位置
                    syncClassGvState();

                    //第二步:设置列表数据
                    classGvAdapter = new ClassGvAdapter(TeacherStudentFileActivity.this, classInfos, R.layout.teacher_gv_class);
                    gv.setAdapter(classGvAdapter);

                    //第三步:设置点击事件
                    gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
                            //记录选中的位置
                            popSelectedPos = pos;

                            //同步GridView的状态,设置列表的选中状态
                            syncClassGvState();

                            //通知适配器刷新
                            classGvAdapter.notifyDataSetChanged();

                            //根据当前选中的班级去请求班级小组的数据
                            httpTeam(popSelectedPos);

                            //延迟关闭弹框
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    PopUpManager.dismiss();
                                }
                            }, 80);

                        }
                    });
                }
            });
        }
    }

    /**
     * 同步班级列表GridView的选中和没选中的状态
     */
    private void syncClassGvState() {
        for (int i = 0; i < classInfos.size(); i++) {
            if (popSelectedPos == i) {
                classInfos.get(i).setSelected(true);
            } else {
                classInfos.get(i).setSelected(false);
            }
        }
    }


    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        if (null != busInfo && TeamRvAdapter.UPDATAPAGEDATA == busInfo.getType()) {
            //重新刷新页面
            httpClass();
        }
    }

    /**
     * 生命周期中释放Handler对象
     */
    @Override
    protected void onDestroy() {
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
        super.onDestroy();
    }
}
